package utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class MailUtils {
	
	private static Properties hostProperties;
	
	public MailUtils() {
		super();
	}
	
	public static String generateMailContent(String htmlFilePath, String company,
			String companyCuit, String campaign, Long campaignYear,
			String status)
	{
		String mailContent = null;
		File mailFile = new File(htmlFilePath);
		FileInputStream fin = null;
		try {
			fin = new FileInputStream(mailFile);
			byte fileContent[] = new byte[(int) mailFile.length()];
			fin.read(fileContent);
			mailContent = new String(fileContent);
			
			mailContent = mailContent.replace("~company~", company);
			mailContent = mailContent.replace("~companyCuit~", companyCuit);
			mailContent = mailContent.replace("~campana~", campaign);
			mailContent = mailContent.replace("~anoCampana~", campaignYear.toString());
			mailContent = mailContent.replace("~estado~", status);
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally
		{
			try {
				fin.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return mailContent;
	}
	
	public static void sendEmail(List<String> sendTo,
			String subject, String content) throws AddressException,
			MessagingException {
		hostProperties = Utils.getProperties("resource/mail.properties");
		
		Session session = Session.getDefaultInstance(hostProperties, null);
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(hostProperties
				.getProperty("mail.smtp.user")));

		InternetAddress[] toAddress = new InternetAddress[sendTo.size()];

		int e = 0;
		while(e < sendTo.size())
		{
			toAddress[e] = new InternetAddress(sendTo.get(e));
			e++;
		}
		
		for (int i = 0; i < toAddress.length; i++) {
			message.addRecipient(Message.RecipientType.BCC, toAddress[i]);
		}
		message.setSubject(subject);
		message.setContent(content, "text/html");

		Transport transport = session.getTransport("smtp");
		
		transport.connect(
				hostProperties.getProperty("mail.smtp.host"),
				hostProperties.getProperty("mail.smtp.user"), 
				hostProperties.getProperty("mail.smtp.password"));
		
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
		
	}
}
